package handler

import (
	"exam/api/request"
	"exam/consts"
	"exam/internal/dao"
	"exam/internal/model"
	"exam/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Register(c *gin.Context) {
	var req request.AddStudent
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.Student
	dao.GetOneByFields(&model.Student{Username: req.Username}, &data)
	if data.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该用户已被注册",
			"data":    nil,
		})
		return
	}

	student := model.Student{
		Username: req.Username,
		Name:     req.Name,
		Password: req.Password,
	}
	if !dao.Create(&student) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "注册失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    student,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}

	var student model.Student
	if !dao.GetOneByFields(&model.Student{Username: req.Username, Password: req.Password}, &student) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "登录失败",
			"data":    nil,
		})
		return
	}

	token, err := pkg.NewJWT(consts.JWT_KEY).CreateToken(pkg.CustomClaims{
		ID: student.Id,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "token生成失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登录成功",
		"data":    token,
	})
}

func UpdateToken(c *gin.Context) {
	token := c.Request.Header.Get("x-token")
	tokens, err := pkg.NewJWT(consts.JWT_KEY).RefreshToken(token)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "token生成失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "token生成成功",
		"data":    tokens,
	})
}
